import { ref } from 'vue'
import { io } from 'socket.io-client'
import { Socket } from 'socket.io-client'
const message = ref('')
const remoteMedia: any = ref()
const videoMedia: any = ref()
const roomId = ref('fanjiantao')
const socket = io('localhost:3000')
socket.connect()
const userId = 'fanjiantao@' + Math.random().toString(16).slice(2)
const toUser = 'fanjiantao2@' + Math.random().toString(16).slice(2)
const pc = new RTCPeerConnection()

socket.on('connect', () => {
  socket.emit('join', { roomId: roomId.value, userId: userId })
  socket.on('offer', (data) => {
    logger('socket-offer', data)
    // offerSdp.value = JSON.stringify(data.offer)
    createAnswer(data.offer)
    // console.log(data, 'fanjiantao2@offer')
  })
  socket.on('answer', (data) => {
    // console.log(data, 'fanjiantao@answer')
    // answerSdp.value = JSON.stringify(data.answer)
    addAnswer(data.answer)
  })

  socket.on('icecandidate', async (data) => {
    // logger('sockte-icecandidate', data)
    await pc.addIceCandidate(data.candidate)
    logger('pc.addIceCandidate-sucess', 'pc 设置Candidate成功')
  })
})

const logger = (name, log) => {
  console.log('-----------' + name + '@satrt-----------')
  console.log(log)
  console.log('-----------' + name + '@end-----------')
  console.log('\n')
}

const sendDisplay = () => {
  getMedia()
}

const getMedia = () => {
  navigator.mediaDevices
    .getDisplayMedia({ audio: true, video: true })
    .then(function (stream: any) {
      // 将视频流赋值给video元素进行展示
      // videoUrl.value = stream
      videoMedia.value.srcObject = stream // console.log(pc)
      // console.log(stream)
      // ;(pc as any).addStream(stream)

      stream.getTracks().forEach((track) => {
        pc.addTrack(track, stream)
      })
      createOffer(socket)
    })
    .catch(function (error) {
      console.log('无法获取视频流', error)
    })
}

const createOffer = async (socket: Socket) => {
  // const offer = await pc.createOffer({
  //   offerToReceiveAudio: false,
  //   offerToReceiveVideo: false
  // })
  const offer = await pc.createOffer()
  logger('pc-createOffer-success', offer.sdp)
  await pc.setLocalDescription(offer)
  logger('pc-setLocalDescription-success', '设置成功local')
  // pc.onconnectionstatechange = (e) => {
  //   logger('pc-connectionstatechange', e)
  // }
  pc.onicecandidate = async (e) => {
    // logger('pc-icecandidate', e.candidate?.candidate)
    if (e.candidate) {
      // await pc.addIceCandidate(e.candidate)
      socket.emit('icecandidate', {
        to: toUser,
        from: userId,
        roomId: roomId.value,
        candidate: e.candidate
      })
      // logger('pc.addIceCandidate-sucess', 'pc 设置Candidate成功')
    }
  }

  socket.emit('offer', { to: toUser, from: userId, roomId: roomId.value, offer: offer })

  //* 发送给pc
  // createAnswer(offer)
}

const createAnswer = async (desc) => {
  // pc.oniceconnectionstatechange = (e) => {
  //   logger('pc-iceconnectionstatechange', e)
  // }
  pc.onicecandidate = async (e) => {
    // logger('pc-icecandidate', e.candidate?.candidate)
    if (e.candidate) {
      // await pc.addIceCandidate(e.candidate)
      socket.emit('icecandidate', {
        to: toUser,
        from: userId,
        roomId: roomId.value,
        candidate: e.candidate
      })
      // logger('pc.addIceCandidate-sucess', 'pc 设置Candidate成功')
    }
  }
  pc.ontrack = (e) => {
    remoteMedia.value.srcObject = e.streams[0]
    logger('pc.ontrack', e.streams[0])
  }
  await pc.setRemoteDescription(desc)
  logger('pc-setRemoteDescription-success', desc)

  const answer = await pc.createAnswer()
  logger('pc.createAnswer-success', answer)
  await pc.setLocalDescription(answer)
  logger('pc.setLocalDescription-success', '设置成功')
  socket.emit('answer', { to: toUser, form: userId, answer: answer, roomId: roomId.value })
}

const addAnswer = async (answer) => {
  await pc.setRemoteDescription(answer)
}
